//
//  PersonalHeaderView.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/20.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit
import RxSwift


class PersonalHeaderView: UIView {
    lazy var avatarImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 50
        imageView.backgroundColor = .imagePlaceholderColor
        imageView.layer.borderWidth = 2
        imageView.layer.borderColor = UIColor.white.cgColor
        let tap = UITapGestureRecognizer(target: self, action: #selector(PersonalHeaderView.avatarDidTap))
        imageView.addGestureRecognizer(tap)
        return imageView
    }()
    
    lazy var nameLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 22.0, weight: .medium)
        label.textAlignment = .center
        label.textColor = .white
        return label
    }()
    
    lazy var uidLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15.0)
        label.textAlignment = .center
        label.textColor = .white
        return label
    }()
    
    let avatarSubject = PublishSubject<Void>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .standardColor
        addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(78)
            make.centerX.equalToSuperview()
            make.height.width.equalTo(100)
        }
        addSubview(nameLabel)
        nameLabel.snp.makeConstraints { (make) in
            make.top.equalTo(avatarImageView.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(27)
        }
        addSubview(uidLabel)
        uidLabel.snp.makeConstraints { (make) in
            make.top.equalTo(nameLabel.snp.bottom).offset(8)
            make.left.right.equalToSuperview()
            make.height.equalTo(18)
        }
        updateUserInfo()
    }
    
    @objc private func avatarDidTap() {
        avatarSubject.onNext(())
    }
    
    func updateUserInfo() {
        let user = AccountManager.share.user
        avatarImageView.kf.setImage(with: URL(string: user.avatarURL), placeholder: nil)
        nameLabel.text = user.name
        uidLabel.text = "ID " + user.uid
        avatarImageView.isUserInteractionEnabled = AccountManager.share.isLogin
    }
}

